import pyglet
from atb import _atb
import atb
from pyglet.window import key
from pyglet.window import mouse

def _make_pyglet_map():
    ret = {}
    import string
    from pyglet.window import key
    for c in string.letters:
        ret[getattr(key, c.upper())] = ord(c)
    for c in string.digits:
        ret[getattr(key, "_"+c)] = ord(c)
    ret.update({
        key.SPACE: ord(' '),
        key.BACKSPACE: ord('\b'),
        key.RETURN: ord('\r'),
        key.PERIOD: ord('.'),
        key.MINUS: ord('-'),
    })
    return ret

_pyglet_key_map = _make_pyglet_map()

_pyglet_button_map = {
    mouse.LEFT: _atb.TW_MOUSE_LEFT,
    mouse.MIDDLE: _atb.TW_MOUSE_MIDDLE,
    mouse.RIGHT: _atb.TW_MOUSE_RIGHT,
}

def map_key(key):
    return _pyglet_key_map[key]

def map_button(button):
    return _pyglet_button_map[button]

def map_modifiers(modifiers):
    ret = _atb.TW_KMOD_NONE
    if modifiers & key.MOD_SHIFT:
        ret |= _atb.TW_KMOD_SHIFT
    if modifiers & key.MOD_CTRL:
        ret |= _atb.TW_KMOD_CTRL
    if modifiers & key.MOD_ALT:
        ret |= _atb.TW_KMOD_ALT
    return ret

class ATBEventHandler(object):

    def __init__(self, window, push_handlers=True):
        self.window = window
        if push_handlers:
            window.push_handlers(self)

    def on_resize(self, width, height):
        atb.resize(width, height)

    def on_key_press(self, symbol, modifiers):
        try:
            _atb.atb_dll.TwKeyPressed(map_key(symbol), map_modifiers(modifiers))
        except KeyError:
            print "cant handle"
        else:
            return True

    def on_mouse_press(self, x, y, button, modifiers):
        _atb.atb_dll.TwMouseButton(_atb.TW_MOUSE_PRESSED, map_button(button))  

    def on_mouse_release(self, x, y, button, modifiers):
        _atb.atb_dll.TwMouseButton(_atb.TW_MOUSE_RELEASED, map_button(button))

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        _atb.atb_dll.TwMouseMotion(x, self.window.height-y)

    def on_mouse_motion(self, x, y, dx, dy):
        _atb.atb_dll.TwMouseMotion(x, self.window.height-y)

    def on_draw(self):
        self.window.clear()
        atb.draw()

